//
//  AppDataManager.m
//  HibuSearch
//
//  Created by leo on 13-6-7.
//  Copyright (c) 2013年 HIBU. All rights reserved.
//

#import "AppDataManager.h"
#import "AppData.h"
#import "FileHelper.h"

static AppDataManager* _obj = nil;

NSString* const kAppDataPath = @"AppData";
NSString* const kAppDataFile = @"AppData.txt";

@interface AppDataManager() {
    
    //instance containing app data
    AppData*    _appData;
}

- (NSString*) appDataFile;
- (AppData*) loadAppData;
- (void) saveAppData;
@end


@implementation AppDataManager

@dynamic isFirstLaunch;

+ (AppDataManager*) sharedInstance {
    
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        _obj = [[self alloc] init];
    });
    
    return _obj;
    
}

- (id) init {
    
    if (self = [super init]) {
        
        _appData = [self loadAppData];
        
        _appData.countOfAppLaunch += 1;
        
        [self saveAppData];
        
#if DEBUG
        NSLog(@"App Data File: %@" ,[self appDataFile]);
#endif
        
    }
    
    return self;
}

- (BOOL) isFirstLaunch {
    
    return _appData.countOfAppLaunch == 1 ? YES : NO;
}

- (BOOL) isSecondLaunch {
    
    return _appData.countOfAppLaunch == 2 ? YES : NO;
}

- (NSInteger)countOfAppLaunch
{
    return _appData.countOfAppLaunch;
}

- (NSString*) appDataFile
{

    
    return [[[FileHelper getDocumentDirectory]
                stringByAppendingPathComponent:kAppDataPath]
                stringByAppendingPathComponent:kAppDataFile];
}

- (AppData*) loadAppData
{
    AppData* appData = [FileHelper decodeContentFromFile:[self appDataFile]];
    
    if (appData == nil) {
        appData = [[AppData alloc] init];
    }
    
    return appData;
}

- (void) saveAppData
{
    [FileHelper encodeContent:_appData toFile:[self appDataFile]];
}

@end
